package server.schedulables;

import java.nio.channels.ClosedChannelException;

import server.NetworkMediator;
import common.Auction;
import common.AuctionExpiration;
import common.PhaseEnum;
import common.Player;

public class ScheduledAuctionExpiration implements Runnable {

	private final NetworkMediator network;
	
	private final Auction auction;
	private final Player player;
	
	public ScheduledAuctionExpiration( NetworkMediator network, Auction auction, Player p ) {
		this.network = network;
		this.auction = auction;
		this.player = p;
	}
	
	public void run() {
		//This auction could have already been removed if successfully matched before expiration
		// but it is still safe to do anyways.
		if( player.removeAuction( auction ) ) {
			// if it actually was removed, aka expired successfully
			// send a packet to the client telling it about the expiration
			
			//If the Auction expired in the Results phase just ignore the expiration.
			if( player.getRound().getCurrentPhase() == PhaseEnum.RESULTS )
				return;
			
			try {
				//Tell all players in the round about the expired auction.
				network.sendToAllInRound( player.getRound(), new AuctionExpiration( auction ) );
//				network.sendTo(player, new AuctionExpiration( auction ) );
			} catch (ClosedChannelException e) {
				e.printStackTrace();
			}
		}
	}

}
